package com.why.websocketmqttstudy.why.websocket.handler;


import com.why.websocketmqttstudy.why.entity.User;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;


import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * MyChannelHandlerPool
 * 通道组池，管理所有websocket连接
 *
 * @author zhengkai.blog.csdn.net
 * @date 2019-06-12
 */
public class ChannelHandlerPool {
    public ChannelHandlerPool() {
    }

    // 全部连接
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    // 每个客户的连接通道，用户编号
    private static ConcurrentMap<String, ChannelId> channelMap = new ConcurrentHashMap();

    // 包括连接用户信息
    private static ConcurrentMap<String, User> userMap = new ConcurrentHashMap();

    private static ConcurrentMap<String, String> userCodeMap = new ConcurrentHashMap();

    public static Channel addChannel(Channel channel, User user) {
        Channel channelByUser = null;
        channelGroup.add(channel);
        channelMap.put(channel.id().asShortText(), channel.id());
        userMap.put(channel.id().asShortText(), user);
        if (userCodeMap.get(user.getUserName()) != null) {
            channelByUser = findChannelByUser(user.getUserName());
            removeChannel(channelByUser);
        }
        userCodeMap.put(user.getUserName(), channel.id().asShortText());
        return channelByUser;
    }

    public static void removeChannel(Channel channel) {
        channelGroup.remove(channel);
        channelMap.remove(channel.id().asShortText());
        userCodeMap.remove(userMap.get(channel.id().asShortText()).getUserName());
        userMap.remove(channel.id().asShortText());
    }

    public static Channel findChannelByUser(String userCode) {
        String id = userCodeMap.get(userCode);
        if (id == null) return null;
        return channelGroup.find(channelMap.get(id));
    }

    public static Channel findChannel(String id) {
        return channelGroup.find(channelMap.get(id));
    }

    public static String findUserCodeByChannel(Channel channel){
        return userMap.get(channel.id().asShortText()).getUserName();
    }
}